<template>
    <Popup :class="`tech-authentication ${mode} ${styleMode}`" v-model="showAuthentication" :close-on-click-overlay="false">
        <div :class="modalClass">
            <div class="modal-title">
                <div class="title-name">{{title}}</div>
                <MiniIcon class="tech-popup-close-icon" name="close" :mode="mode" theme="#7D7D83" :styleMode="styleMode" is-stop @click="cancel" />
            </div>
            <div class="modal-content">
                <template v-if="type === 'password'">
                    <div class="auth-tip">输入数字支付密码进行身份验证</div>
                    <PasswordInput :value="password" @focus="showKeyboard = true" />
                    <div v-if="!isOnlyType" class="forget-pass"><span @click="type = 'phonecode'">忘记密码？</span></div>
                </template>
                <template v-else>
                    <div class="phone-code-tip">输入短信验证码进行身份验证</div>
                    <Field v-model="phone" type="number" :disabled="true" @blur="inputOnBlur" placeholder="输入您的手机号" />
                    <Field v-model="code" type="number" placeholder="输入验证码" @blur="inputOnBlur" :maxlength="4">
                        <Button v-if="isWait" class="get-code" type="default" plain size="small" slot="button" :disabled="true">{{`${times}s后重发`}}</Button>
                        <Button v-else class="get-code" type="danger" plain size="small" slot="button" @click="getCode">获取验证码</Button>
                    </Field>
                    <div class="btn-list">
                        <Button :disabled="isLoading" @click="close">取消</Button>
                        <Button type="danger" :disabled="isDisabled" :loading="isLoading" @click="authentication">确定</Button>
                    </div>
                </template>
            </div>
        </div>
        <NumberKeyboard :show="showKeyboard" @input="onInput" @delete="onDelete" @blur="showKeyboard = false" />
    </Popup>
</template>

<script>
import { Popup, PasswordInput, NumberKeyboard, Field, Button } from 'vant';
import { mapState, mapActions } from 'vuex';
import { MiniIcon } from '@components/base';
import { getUserMemberIdCookie } from '@biztools/info';
import { sendVerifyCode, checkVerifyCode, checkPassword } from '@common/market';
import { inputBlurAction } from '@common/utils';
import ModeMixin from '@common/mixin';
export default {
    name: 'Authentication',
    mixins: [ModeMixin],
    props: {
        title: {
            type: String,
            default: '身份验证',
        },
        authType: {
            type: String,
            default: 'password', // 认证方式，password，phonecode 默认为：password
        },
        isOnlyType: {
            type: Boolean,
            default: false,
        },
    },
    components: {
        Popup,
        PasswordInput,
        NumberKeyboard,
        Button,
        Field,
        MiniIcon,
    },
    computed: {
        ...mapState({
            phone: state => state.member.memberInfo.mobile,
            memberId: state => state.member.memberId || getUserMemberIdCookie(),
        }),
        modalClass() {
            const { mode, styleMode } = this.$props;
            return `tech-modal ${this.showKeyboard ? 'show-keyboard' : ''} ${mode} ${styleMode}`;
        },
        isDisabled() {
            return (this.phone || '').trim() === '' || this.code.trim() === '';
        },
    },
    data() {
        return {
            showAuthentication: false,
            showKeyboard: false,
            password: '',
            code: '',
            isWait: false,
            times: 35,
            isLoading: false,
            type: 'password', // 认证方式，password，phonecode 默认为：password
        };
    },
    mounted() {
        const { authType } = this.$props;
        this.type = authType || 'password';
        this.showKeyboard = authType === 'password';
    },
    watch: {
        password(val, oldVal) {
            if (val.length === 6) {
                this.authentication();
                this.showKeyboard = false;
            }
        },
        authType(val, oldVal) {
            this.type = val;
            this.showKeyboard = val === 'password';
        },
    },
    methods: {
        show() {
            this.showAuthentication = true;
        },
        close() {
            this.showAuthentication = false;
            clearInterval(this.code_interval);
            Object.assign(this.$data, {
                showAuthentication: false,
                showKeyboard: false,
                password: '',
                code: '',
                isWait: false,
                times: 35,
                isLoading: false,
            });
        },
        inputOnBlur() {
            inputBlurAction();
        },
        cancel() {
            this.$emit('cancel');
            this.close();
        },
        onInput(key) {
            this.password = (this.password + key).slice(0, 6);
        },
        onDelete() {
            this.password = this.password.slice(0, this.password.length - 1);
        },
        getCode() {
            // 获取验证码
            this.isWait = true;
            this.isLoading = false;
            const flag = sendVerifyCode(this.phone);
            if (flag) {
                this.code_interval = setInterval(() => {
                    if (this.times > 0) {
                        this.times--;
                    } else {
                        this.isWait = false;
                        this.times = 35;
                        clearInterval(this.code_interval);
                    }
                }, 1000);
            }
        },
        async authentication() {
            let result = false;
            this.isLoading = true;
            // 验证
            if (this.type === 'password') {
                result = await checkPassword(this.memberId, this.password);
            } else if (this.type === 'phonecode') {
                result = await checkVerifyCode(this.phone, this.code);
            }
            this.$emit('authResult', result);
            this.close();
        },
    },
};
</script>

<style lang="less">
.tech-authentication {
    width: 100%;
    height: 100%;
    .flex-column-center();
    background-color: transparent !important;
    .tech-modal {
        width: 90%;
        position: relative;
        .style-mode();
        &.show-keyboard {
            .m-t(-160);
        }
    }
    .auth-tip {
        color: @text-color;
        .t-c();
        .font-size();
        .m-v(@gap-md);
    }
    .forget-pass {
        .t-r();
        .m-t(@gap);
        > span {
            color: @gray-dark;
        }
    }
    .phone-code-tip {
        color: @gray-darker;
        .font-size();
        .t-l();
        .m-b(@gap);
    }
    .modal-content {
        .van-field {
            border: @border;
            border-radius: @border-radius / 2;
            .m-b(@gap-md);
            &::after {
                border: none;
            }
        }
        .get-code {
            border: none;
        }
    }
    .btn-list {
        .flex-row-center();
        .van-button {
            width: 48%;
            &:last-child {
                margin-left: 4%;
            }
        }
    }
    .van-password-input {
        .m(0);
    }
    [class*=van-hairline]::after {
        border-color: @gray-dark;
    }
}
</style>

